const sequelize = require('../../core/db');
const {Model, DataTypes} = require('sequelize');
const ArticleTag = require('./ArticleTag');
const User = require('./User');

class Article extends Model {

  /**
   * 查询 最新 或 最热 文章列表
   * @param order_by
   * @param page_number
   * @param filter
   * @return {Promise<{page_number, count: any, rows: any}>}
   */
  static async getArticlesByPageNumber({order_by = 'NEWEST', page_number = 1, filter}) {
    switch (order_by) {
      case "NEWEST":
        order_by = [['createdAt', 'DESC']];
        break;
      case "POPULAR":
        order_by = [['view_count', 'DESC']];
        break;
      default:
        order_by = null;
    }
    const attributes = {
      include: [
        [sequelize.fn('DATE_FORMAT', sequelize.col('Article.createdAt'), '%Y-%m-%d %H:%i:%s'), 'createdAt']
        //TODO 注意这里↑必须叫这个名(createdAt) 否则会报SequelizeDatabaseError: Unknown column 'Article.createdAt' in 'order clause' 这是因为我们下面排除了原本的createdAt 而排序又要用到 ORDER BY `Article`.`createdAt` DESC;
        //  并且就算我们更改排序所用到的字段名 也是不行的 比如我们将排序字段名更改为created_at,然后将我们这里生成的新的createdAt也命名为created_at,仍然会报错: SequelizeDatabaseError: Unknown column 'Article.created_at' in 'order clause'


        , [sequelize.fn('DATE_FORMAT', sequelize.col('Article.updatedAt'), '%Y-%m-%d %H:%i:%s'), 'updatedAt']
      ]
      , exclude: ['deletedAt', 'content','createdAt','updatedAt']
    };
    const include = [{
      model: ArticleTag
      , attributes: ['id', 'name']
      , through: {
        attributes: []
      }
    }, {
      model: User
      , attributes: ['id', 'nickname']
    }];
    return await this.findListByPageNumber({
      order_by,
      page_number: parseInt(page_number),
      attributes,
      include,
      filter
    });
  }

  /**
   * 根据id获取文章详情
   * @param id
   * @return {Promise<<Article | null>>}
   */
  static async getArticleDetailById(id){
    return this.findByPk(id, {
      attributes: {
        include: [
          [sequelize.fn('DATE_FORMAT', sequelize.col('Article.createdAt'), '%Y-%m-%d %H:%i:%s'), 'created_at']
          //TODO ↑注意 这里必须这样,`xx.yy`的形式引用字段作为参数,否则会报： SequelizeDatabaseError: Column 'createdAt' in field list is ambiguous

          , [sequelize.fn('DATE_FORMAT', sequelize.col('Article.updatedAt'), '%Y-%m-%d %H:%i:%s'), 'updated_at']
        ]
        , exclude: ['deletedAt','createdAt','updatedAt']
      }
      ,include: [{
        model: ArticleTag
        , attributes: ['id', 'name']
        , through: {
          attributes: []
        }
      }, {
        model: User
        , attributes: ['id', 'nickname']
      }]
    });
  }
}

Article.init({
  id: {
    type: DataTypes.INTEGER.UNSIGNED
    , primaryKey: true
    , autoIncrement: true
  }
  , title: {
    type: DataTypes.STRING
    , defaultValue: ''
    , allowNull: false
    , unique: true
  }
  , content: {
    type: DataTypes.TEXT
    , defaultValue: ''
    , allowNull: false
  }
  // 文章简介
  , introduction: DataTypes.STRING
  , view_count: {
    type: DataTypes.INTEGER
    , defaultValue: 0
    , allowNull: false
  }
}, {
  sequelize
  , tableName: 'article'
});

module.exports = Article;
